package com.swotxu.screwweb.service;

import cn.smallbun.screw.core.engine.EngineFileType;
import com.swotxu.screwweb.config.ScrewProperties;
import com.swotxu.screwweb.util.ReentrantReadWriteLockUtil;
import com.swotxu.screwweb.util.ScrewUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Date: 2021/7/15 20:15
 * @Author: xu.hai
 */
@Service
public class AsyncService {

    private static final Logger log = LoggerFactory.getLogger(AsyncService.class);

    @Autowired
    ReentrantReadWriteLockUtil lockUtil;

    /**
     * 异步覆盖写
     * @param dbInfo 数据库配置
     */
    @Async
    public void asyncOverrideFile(ScrewProperties.ScrewDBInfo dbInfo) {
        // 尝试每个文件类型
        for (EngineFileType fileType : EngineFileType.values()) {
            File docPath = dbInfo.getDocPath(fileType);
            // 文件存在时，获取写锁生成文件覆盖
            if (docPath.exists()) {
                log.info(">> [Async]旧文件存在，开始尝试获取写锁! {}", docPath);
                ReentrantReadWriteLock.WriteLock writeLock = lockUtil.getWriteLock(dbInfo.getId());
                try {
                    writeLock.lock();
                    log.info("写锁获取成功，开始覆盖写入文件! {}", docPath);
                    ScrewUtil.create(dbInfo, fileType);
                } finally {
                    writeLock.unlock();
                }
            }
        }
    }
}
